<?php
namespace Home\Controller;

use Think\Controller;
use Common\Service\Curl;
use Think\Log;
use Admin\Controller\QiniuController;
use Common\Service\Sms;

class UserController extends Controller
{
    public function token(){
        $userId = I('userId', '', 'trim');

        if(!$userId){
            $this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'请登录']);
        }

        $Qiniu = new QiniuController();
        $token = $Qiniu->getToken();
        $this->ajaxReturn(['status'=>true, 'code'=>1000, 'msg'=>'注册成功', 'data'=>['token'=>$token,'url'=>C('qiniu_config')['domain']]]);
    }

	/**
     * 用户注册
     */
    public function register()
    {
    	$mobile    = I('mobile', '', 'trim');
        $password = I('password', '', 'trim');
        $smsCode = I('smsCode', '', 'trim');
        $inviteCode = I('inviteCode', '', 'trim');
        $imei = I('IMEI', '', 'trim');

    	if(!preg_match("/^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0-9]))\\d{8}$/",$mobile)){
    		$this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'手机号错误']);
    	}

    	if(!$password){
    		$this->ajaxReturn(['status'=>false, 'code'=>1002, 'msg'=>'请设置密码']);
    	}

    	$uinfo = M('user')->where(['mobile'=>$mobile])->find();


        if($inviteCode != $uinfo['code']){
            $this->ajaxReturn(['status'=>false, 'code'=>1006, 'msg'=>'请输入正确的邀请码']);
        }

        Log::write($smsCode.'~~~~~~~~~'.S($mobile));
        if(empty($smsCode) || $smsCode != S($mobile)){
            $this->ajaxReturn(['status'=>false, 'code'=>1003, 'msg'=>'请输入正确的验证码']);
        }
        
        
        if($uinfo['status'] == 2){
            $this->ajaxReturn(['status'=>false, 'code'=>1004, 'msg'=>'手机号已注册']);
        }

    	$arr = [
			'mobile'      => $mobile,
            'password'    => $password,
            'status'      => 2,
            'imei'        => $imei,
            'addtime' 	  => time(),
            'updatetime'  => time()
		];
    	$res = M('user')->where(['id'=>$uinfo['id']])->save($arr);
    	if($res){
          
    		$this->ajaxReturn(['status'=>true, 'code'=>1000, 'msg'=>'注册成功', 'data'=>['mobile'=>$mobile,'id'=>$res,'nickName'=>$uinfo['nickName'],'headUrl'=>'']]);
    	}else{
    		$this->ajaxReturn(['status'=>false, 'code'=>1005, 'msg'=>'未知错误']);
    	}
    }

    /**
     * 用户登录
     */
    public function login()
    {
        $mobile    = I('mobile', '', 'trim');
        $password = I('password', '', 'trim');
        $imei = I('IMEI', '', 'trim');

        if(!preg_match("/^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0-9]))\\d{8}$/",$mobile)){
            $this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'手机号错误']);
        }

        if($password == ''){
            $this->ajaxReturn(['status'=>false, 'code'=>1002, 'msg'=>'请输入密码']);
        }

        if($imei == ''){
            $this->ajaxReturn(['status'=>false, 'code'=>1003, 'msg'=>'非法登录']);
        }

        Log::write("imei".$imei);

        $userInfo = M('user')->where(['mobile'=>$mobile])->find();
        if($userInfo){

            if($userInfo['imei'] == ''){
                M("user")->where(['mobile'=>$mobile])->save(['imei'=>$imei]);
            }else{
                if($imei != $userInfo['imei']){
                    $this->ajaxReturn(['status'=>false, 'code'=>1004, 'msg'=>'非常用设备登录，请联系管理员']);
                }
            }

            $res = M('user')->where(['mobile'=>$mobile,'password'=>$password])->find();
            if($res){
                $data = [
                    'id'=>$res['id'],
                    'mobile'=>$res['mobile'],
                    'nickName'=>$res['nickname'],
                    'headUrl'=>$res['headimg'],
                    'description' => $res['description'],
                ];
                
                $ret = ['status'=>true, 'code'=>1000, 'msg'=>'登陆成功', 'data'=>$data];
                $this->ajaxReturn($ret);

            }else{
                $this->ajaxReturn(['status'=>false, 'code'=>1003, 'msg'=>'密码错误']);
            }    
        }else{
            $this->ajaxReturn(['status'=>false, 'code'=>1004, 'msg'=>'请输入正确的手机号']);
        }      
    }

    /**
     * 用户设置,修改密码
     */
    public function editPwd()
    {
        $userId = I('userId', '', 'trim');
        $oldPwd = I('oldPwd', '', 'trim');
        $newPwd = I('newPwd', '', 'trim');

        if(!$userId || !$newPwd){
            $this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'请填写完整用户信息']);
        }

        $userInfo = M('user')->where(['id'=>$userId])->find();
        if($userInfo['password']){
            if(!$oldPwd || $oldPwd != $userInfo['password']){
                $this->ajaxReturn(['status'=>false, 'code'=>1002, 'msg' =>'请填写正确的原始密码！']);
            }
        }

        $rs = M('user')->where(['id'=>$userId])->save(['password'=>$newPwd]);
        if($rs){
            $this->ajaxReturn(['status'=>true, 'code'=>1000, 'msg' =>'设置密码成功！']);
        }else{
            $this->ajaxReturn(['status'=>false, 'code'=>1003, 'msg' =>'设置密码失败！']);
        }
    }

    /**
     * 用户设置,修改密码
     */
    public function findPwd()
    {
        $smsCode = I('smsCode', '', 'trim');
        $mobile = I('mobile', '', 'trim');
        $password = I('password', '', 'trim');

        if(!preg_match("/^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0-9]))\\d{8}$/",$mobile)){
            $this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'手机号错误']);
        }

        if(!$password){
            $this->ajaxReturn(['status'=>false, 'code'=>1002, 'msg'=>'请输入密码']);
        }

        $uinfo = M('user')->where(['mobile'=>$mobile])->find();

        Log::write($smsCode.'~~~~~~~~~'.S($mobile));
        if(empty($smsCode) || $smsCode != S($mobile)){
            $this->ajaxReturn(['status'=>false, 'code'=>1003, 'msg'=>'请输入正确的验证码']);
        }        
        
        // if($uinfo['status'] == 2){
        //     $this->ajaxReturn(['status'=>false, 'code'=>1004, 'msg'=>'手机号已注册']);
        // }

        $rs = M('user')->where(['mobile'=>$mobile])->save(['password'=>$password]);
        if($rs){
            $this->ajaxReturn(['status'=>true, 'code'=>1000, 'msg' =>'设置密码成功！']);
        }else{
            $this->ajaxReturn(['status'=>false, 'code'=>1003, 'msg' =>'设置密码失败！']);
        }
    }

    /**
     * 用户信息更新
     */
    public function update()
    {
        $info = I('','', 'trim');
        if(isset($info['nickName'])){
            $data['nickname'] = $info['nickName'];  
        }

        if(isset($info['headimg'])){
            $data['headimg'] = $info['headimg']; 
        }

        if(isset($info['description'])){
            $data['description'] = $info['description']; 
        }

        if(isset($info['remark'])){
            $data['remark'] = $info['remark']; 
        }
        
        $data['update_time'] = time(); 
        
        $rs = M('user')->where(['id'=>$info['userId']])->find();
        if(!$rs){
            $this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'用户id异常']);
        }

        $res = M('user')->where(['id'=>$info['userId']])->save($data);
        if($res){
            $this->ajaxReturn(['status'=>true, 'code'=>1000, 'msg'=>'更新成功']);
        }else{
            $this->ajaxReturn(['status'=>false, 'code'=>1002, 'msg' =>'数据库更新失败']);
        }
    }

    /**
     * 我的关注
     */
    public function follow(){
    	$userId = I('userId', '', 'trim');
		$page = I('page', '1', 'trim');
        $size = I('size', '5', 'trim'); 
        $firstNum = ($page-1)*$size;

        if(!$userId){
        	$this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'请登录']);
        }

        $map['user_id'] = $userId;

		$model = M('user_follow as s');
		$res = $model
			->where($map)
			->join('left join wk_teacher as t on t.id=s.teacher_id')
			->field('s.id userId,t.id techerId,t.mobile,t.nickname,t.remark,t.headimg')
			->limit($firstNum,$size)
			->select();

		if($page == 1 && !$res){
            $this->ajaxReturn(['status'=>true, 'code'=>1000, 'msg'=>'无关注信息', 'data'=>[]]);
        }
    
        if($page > 1 && !$res){
            $this->ajaxReturn(['status'=>false, 'code'=>1002, 'msg'=>'无更多关注信息', 'data'=>[]]);
        }


		$this->ajaxReturn(['status' => true, 'code'=>1000,'msg' => '查询成功','data'=>$res]);
    }

    /**
     * 操作我的关注
     * $type  1=>关注 2=>取消
     */
    public function doFollow(){
        $userId = I('userId', '', 'trim');
        $teacherId = I('teacherId', '', 'trim');
        $type = I('type', '1', 'trim');

        if(!$userId){
            $this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'请登录']);
        }

        $info = M('user_follow')->where(['user_id'=>$userId,'teacher_id'=>$teacherId])->find();
        $vinfo = M('teacher')->where(['id'=>$teacherId])->find();

        if(!$vinfo){
            $this->ajaxReturn(['status'=>false, 'code'=>1003, 'msg'=>'参数错误']);
        }
        
        if($type == 1){
            //添加
            if($info){
                $this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'您已经关注过该艺术家']);
            }else{
                $data = [   
                            'user_id'  => $userId,
                            'teacher_id' => $teacherId,
                            'status'   => 1,
                            'addtime'  => time()
                        ];
                if(M('user_follow')->add($data)){
                    $this->ajaxReturn(['status' => true, 'code'=>1000,'msg' => '关注成功','data'=>[]]);
                }
            }
        }else{
            //删除
            if(!$info){
                $this->ajaxReturn(['status'=>false, 'code'=>1002, 'msg'=>'您当前未关注该艺术家，无法删除']);
            }

            $d = M('user_follow')->where(['user_id'=>$userId,'teacher_id'=>$teacherId])->delete();

            if($d){
                $this->ajaxReturn(['status' => true, 'code'=>1000,'msg' => '取消关注成功','data'=>[]]);
            }

        }

    }

    /**
     * 我的收藏
     */
    public function collect(){
    	$userId = I('userId', '', 'trim');
		$page = I('page', '1', 'trim');
        $size = I('size', '5', 'trim'); 
        $firstNum = ($page-1)*$size;

        if(!$userId){
        	$this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'请登录']);
        }

        $map['user_id'] = $userId;

		$model = M('user_collect as s');
		$res = $model
			->where($map)
			->join('left join wk_video as t on t.id=s.video_id')
			->field('s.id userId,t.id videoId,t.title,t.description,t.surface_img,t.remark,t.video_url videoUrl')
            ->where(['t.id'=>['neq','']])
			->limit($firstNum,$size)
			->select();

		if($page == 1 && !$res){
            $this->ajaxReturn(['status'=>true, 'code'=>1000, 'msg'=>'无关注信息', 'data'=>[]]);
        }
    
        if($page > 1 && !$res){
            $this->ajaxReturn(['status'=>false, 'code'=>1002, 'msg'=>'无更多关注信息', 'data'=>[]]);
        }


		$this->ajaxReturn(['status' => true, 'code'=>1000,'msg' => '查询成功','data'=>$res]);
    }

    /**
     * 操作我的收藏
     * $type  1=>添加 2=>取消
     */
    public function doCollect(){
        $userId = I('userId', '', 'trim');
        $videoId = I('videoId', '', 'trim');
        $type = I('type', '1', 'trim');

        if(!$userId){
            $this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'请登录']);
        }

        $info = M('user_collect')->where(['user_id'=>$userId,'video_id'=>$videoId])->find();
        $vinfo = M('video')->where(['id'=>$videoId])->find();

        if(!$vinfo){
            $this->ajaxReturn(['status'=>false, 'code'=>1003, 'msg'=>'参数错误']);
        }
        
        if($type == 1){
            //添加
            if($info){
                $this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'您已经收藏过该信息']);
            }else{
                $data = [   
                            'user_id'  => $userId,
                            'video_id' => $videoId,
                            'status'   => 1,
                            'addtime'  => time()
                        ];
                if(M('user_collect')->add($data)){
                    $this->ajaxReturn(['status' => true, 'code'=>1000,'msg' => '收藏成功','data'=>[]]);
                }
            }
        }else{
            //删除
            if(!$info){
                $this->ajaxReturn(['status'=>false, 'code'=>1002, 'msg'=>'您当前未收藏该信息，无法删除']);
            }

            $d = M('user_collect')->where(['user_id'=>$userId,'video_id'=>$videoId])->delete();

            if($d){
                $this->ajaxReturn(['status' => true, 'code'=>1000,'msg' => '取消收藏成功','data'=>[]]);
            }

        }

    }

    /**
     * 发送验证码
     */
    public function smscode(){
        $mobile = I('mobile', '', 'trim');

        if(!preg_match("/^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0-9]))\\d{8}$/",$mobile)){
            $this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'手机号错误']);
        }

        $uinfo = M('user')->where(['mobile'=>$mobile])->find();

        if(!$uinfo){
            $this->ajaxReturn(['status'=>false, 'code'=>1001, 'msg'=>'手机号不在邀约注册名单']);
        }

        $res = Sms::NewSms($mobile);
        if($res){
            $arr = [
                'mobile'=>$mobile,
                'code' =>$res,
                'status' => 1,
                'addtime' =>time(),
           ];
            M('sms_code')->add($arr);

            $this->ajaxReturn(['status' => true, 'code'=>1000,'msg' => '短信发送成功','data'=>['mobile'=>$mobile,'num'=>$res]]);
        }

        $this->ajaxReturn(['status' => false, 'code'=>1004,'msg' => '短信发送失败']);
    }



}